#! /usr/bin env python
# coding:utf-8
import sys, getopt, time
import threading
from espider.app.ppb.ppb_logic import PpbLogic
import redis


class PpbRedis(threading.Thread):
    def __init__(self, kwargs):
        threading.Thread.__init__(self, target=self.work, kwargs=kwargs)
        self.logic = PpbLogic()
        # 创建一个Redis连接
        self.r = redis.Redis(host='10.16.3.6', port=6379, db=0)
        # 测试数据：设置键值对
        self.r.set('globalkey', 'yes')

    def work(self, *args, **kwargs):
        totalreq = kwargs["totalreq"]
        print("每个客户端发送 %s 个请求" % totalreq)
        for i in range(totalreq):
            # 获取键值
            value = self.r.get('globalkey')
            print("key的值是：", value)
            # 每个请求暂停100毫秒
            time.sleep(1)


if __name__ == "__main__":
    argv = sys.argv[1:]
    requests = clients = 0
    try:
        opts, args = getopt.getopt(argv, "hc:r:", ["clients=", "requests="])
    except getopt.GetoptError:
        print('python3 ppb_redis.py -c <客户端个数> -r <请求个数>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('python3 ppb_redis.py -c <客户端个数> -r <请求个数>')
            sys.exit()
        elif opt in ("-c", "--clients"):
            clients = int(arg)
        elif opt in ("-r", "--requests"):
            requests = int(arg)
    if 0 == clients or 0 == requests:
        print('python3 ppb_redis.py -c <客户端个数> -r <请求个数>')
        sys.exit(2)
    totalreq = int(requests / clients)
    kwargs = {"totalreq": totalreq}
    for i in range(clients):
        pb = PpbRedis(kwargs)
        pb.start()
